<?php

namespace App\Models\User;

use Illuminate\Database\Eloquent\Model;

class LiveUserFollow extends Model
{
    public $table = 'live_user_follow';
    public $timestamps = false;

    public function getCreatedTimeAttribute($val)
    {
        return date('Y-m-d',$val);
    }

    #更新或创建关注记录
    public static function createOrUpdate($user_id,$to_user_id)
    {
        $collect  = self::query()->where('user_id','=',$user_id)->where('to_user_id','=',$to_user_id)->first();
        if (empty($collect)) {
            $flag = self::insert([
                'user_id'       => $user_id,
                'to_user_id'    => $to_user_id,
                'created_time'  => time(),
            ]);
        } else {
            $collect->status = !$collect->status;
            $flag = $collect->save();
        }
        if (empty($flag)) {
            return false;
        }
        return true;
    }

    #根据用户id获取关注列表
    public static function getFollowByUserId($user_id)
    {
        $data = self::with('user')
                    ->where('user_id','=',$user_id)
                    ->where('status','=',1)
                    ->paginate(15)
                    ->toArray();
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #关联用户表
    public function user()
    {
        return $this->hasOne(LiveUser::class,'id','to_user_id')->select('id','user_name','user_avatar')->withDefault([
            'user_name'     => '',
            'user_avatar'   => '',
        ]);
    }
}
